package mobi.greenplate.client.connect;

import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.auth.AuthScope;

import org.apache.http.auth.Credentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 *
 * @author dmakariev
 */
class HttpClientHelper {

    public static HttpClientHelper connect(ConnectionContext connectionContext) {
        return new HttpClientHelper(connectionContext);
    }

    public int executeGet(HttpClientTemplateContext context) {
        final HttpClientTemplate getTemplate = new GetTemplate(context);
        return execute(getTemplate);
    }

    public int executePost(HttpClientTemplateContext context) {
        final HttpClientTemplate getTemplate = new PostTemplate(context);
        return execute(getTemplate);
    }

    public int executePut(HttpClientTemplateContext context) {
        final HttpClientTemplate getTemplate = new PutTemplate(context);
        return execute(getTemplate);
    }

    public int executeDelete(HttpClientTemplateContext context) {
        final HttpClientTemplate getTemplate = new DeleteTemplate(context);
        return execute(getTemplate);
    }

    private HttpClientHelper(ConnectionContext connectionContext) {
        this.connectionContext = connectionContext;
    }
    private final ConnectionContext connectionContext;

    private AuthScope getAuthScope() {
        return new AuthScope(getConnectionContext().getServerName(), getConnectionContext().getServerPort());
    }

    private Credentials getCredentials() {
        final String userName = getConnectionContext().getUserName();
        final String password = getConnectionContext().getPassword();
        return new UsernamePasswordCredentials(userName, password);
    }

    private ConnectionContext getConnectionContext() {
        return connectionContext;
    }

    private HttpClient getHttpClient() {
        final DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
        httpclient.getCredentialsProvider().setCredentials(getAuthScope(), getCredentials());
        return httpclient;

    }

    private int execute(HttpClientTemplate template) {
        int statusCode = -1;
        try {
            final HttpClient httpClient = getHttpClient();

            statusCode = template.execute(httpClient);

            httpClient.getConnectionManager().shutdown();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return statusCode;
    }
}
